/**
 * 
 */
package com.kelaite.procurement.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.kelaite.procurement.common.CommonResponseDto;
import com.kelaite.procurement.common.RetCodeEnum;
import com.kelaite.procurement.constants.BidTypeEnum;
import com.kelaite.procurement.constants.BizType;
import com.kelaite.procurement.constants.Constants;
import com.kelaite.procurement.constants.CurrencyTypeEnum;
import com.kelaite.procurement.constants.UserTypeEnum;
import com.kelaite.procurement.dto.CompanyDTO;
import com.kelaite.procurement.dto.MaterialMasterClientDTO;
import com.kelaite.procurement.dto.PageDTO;
import com.kelaite.procurement.dto.PipelineItemDTO;
import com.kelaite.procurement.dto.PipelinePublicDTO;
import com.kelaite.procurement.dto.PurchaseOrderDTO;
import com.kelaite.procurement.dto.PurchaseOrderExecutionItemsDTO;
import com.kelaite.procurement.dto.PurchaseOrderItemsDTO;
import com.kelaite.procurement.dto.PurchaseOrderPaymentDTO;
import com.kelaite.procurement.dto.PurchaseOrganizationDTO;
import com.kelaite.procurement.dto.UnitDTO;
import com.kelaite.procurement.dto.UserDTO;
import com.kelaite.procurement.entity.TCompany;
import com.kelaite.procurement.entity.TDemand;
import com.kelaite.procurement.entity.TIndustry;
import com.kelaite.procurement.entity.TMessage;
import com.kelaite.procurement.entity.TMaterialMasterClient;
import com.kelaite.procurement.entity.TPipelineHeader;
import com.kelaite.procurement.entity.TPipelineItem;
import com.kelaite.procurement.entity.TPipelinePublic;
import com.kelaite.procurement.entity.TProvince;
import com.kelaite.procurement.entity.TPurchaseOrder;
import com.kelaite.procurement.entity.TPurchaseOrderItems;
import com.kelaite.procurement.entity.TPurchaseOrderPayment;
import com.kelaite.procurement.entity.TPurchaseOrganizationUser;
import com.kelaite.procurement.entity.TSalesOrderPayment;
import com.kelaite.procurement.entity.TUser;
import com.kelaite.procurement.entity.TVendor;
import com.kelaite.procurement.entity.TVendorHistory;
import com.kelaite.procurement.exception.AmountExceedLimitException;
import com.kelaite.procurement.exception.BusinessException;
import com.kelaite.procurement.exception.DuplicateObjectException;
import com.kelaite.procurement.exception.NullObjectException;
import com.kelaite.procurement.exception.SubmitZeroItemsException;
import com.kelaite.procurement.restful.BaseController;
import com.kelaite.procurement.service.CompanyService;
import com.kelaite.procurement.service.DemandService;
import com.kelaite.procurement.service.IndustryService;
import com.kelaite.procurement.service.MessageService;
import com.kelaite.procurement.service.MaterialMasterClientService;
import com.kelaite.procurement.service.PipelineHeaderService;
import com.kelaite.procurement.service.PipelineItemService;
import com.kelaite.procurement.service.PipelinePublicService;
import com.kelaite.procurement.service.ProvinceService;
import com.kelaite.procurement.service.PurchaseOrderExecutionItemsService;
import com.kelaite.procurement.service.PurchaseOrderExecutionService;
import com.kelaite.procurement.service.PurchaseOrderItemsService;
import com.kelaite.procurement.service.PurchaseOrderPaymentService;
import com.kelaite.procurement.service.PurchaseOrderService;
import com.kelaite.procurement.service.PurchaseOrganizationService;
import com.kelaite.procurement.service.PurchaseOrganizationUserService;
import com.kelaite.procurement.service.SalesOrderExecutionService;
import com.kelaite.procurement.service.SalesOrderPaymentService;
import com.kelaite.procurement.service.SalesOrderService;
import com.kelaite.procurement.service.UnitService;
import com.kelaite.procurement.service.UserService;
import com.kelaite.procurement.service.VendorService;
import com.kelaite.procurement.service.VendorUserService;
import com.kelaite.procurement.utils.CommonUtils;
import com.kelaite.procurement.utils.ConvertTime;
import com.kelaite.procurement.utils.CurrentUserUtils;
import com.kelaite.procurement.utils.JsonUtil;

/**
 * @author think
 *
 */
@Controller
@RequestMapping("/client/")
public class ClientController extends BaseController {

	@Autowired
	private PipelineHeaderService pipelineHeaderService;

	@Autowired
	private PipelineItemService pipelineItemService;

	@Autowired
	private PipelinePublicService pipelinePublicService;

	@Autowired
	private VendorService vendorService;

	@Autowired
	private UserService userService;

	@Autowired
	private ProvinceService provinceService;

	@Autowired
	private PurchaseOrganizationService purchaseOrganizationService;

	@Autowired
	private VendorUserService vendorUserService;

	@Autowired
	private PurchaseOrderService purchaseOrderService;

	@Autowired
	private PurchaseOrderPaymentService purchaseOrderPaymentService;

	@Autowired
	private PurchaseOrderItemsService purchaseOrderItemsService;

	@Autowired
	private UnitService unitService;

	@Autowired
	private IndustryService industryService;

	@Autowired
	private CompanyService companyService;

	@Autowired
	private PurchaseOrganizationUserService purchaseOrganizationUserService;

	@Autowired
	private DemandService demandService;

	@Autowired
	private MessageService messageService;

	@Autowired
	private MaterialMasterClientService materialMasterClientService;

	@Autowired
	private PurchaseOrderExecutionService purchaseOrderExecutionService;

	@Autowired
	private SalesOrderService salesOrderService;

	@Autowired
	private PurchaseOrderExecutionItemsService purchaseOrderExecutionItemService;

	@Autowired
	private SalesOrderPaymentService salesOrderPaymentService;

	@Autowired
	private SalesOrderExecutionService salesOrderExecutionService;

	@InitBinder
	public void initBinder(WebDataBinder binder) {

		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(true);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

	@RequestMapping(value = "/index", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String index(Model model) {

		// TODO
		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
		// 查询user
		TUser currentUser = this.userService.getObject(userDTO.getId());
		// 查询t_purchase_order status:0&1 daichuli
		List<TVendor> vendorList = this.vendorService.getByProperty("tClient",
				currentUser.gettCompany());

		List<TPurchaseOrder> tPurchaseOrder = this.purchaseOrderService
				.getByProperty("tCompany", currentUser.gettCompany());
		// 查询T_pipeline_lineitem daizhaobiao
		List<TPipelineItem> lines = this.pipelineItemService.getByProperty(
				"createdBy", "" + userDTO.getId());
		// 查询T_vendor status:1 daishenhe
		List<TVendor> tVendor = this.vendorService.getByProperty("status",
				(short) 1);
		// 查询T_message message read_status:0 message
		List<TMessage> tMessages = this.messageService.getByProperty(
				"readStatus", 0);

		int daichuli = 0;
		int daizhaobiao = lines.size();
		int daishenhe = tVendor.size();
		int message = tMessages.size();
		for (int i = 0; i < tPurchaseOrder.size(); i++) {
			if (tPurchaseOrder.get(i).getOrderStatus() == 0
					|| tPurchaseOrder.get(i).getOrderStatus() == 1) {
				daichuli = daichuli + 1;
			}
		}
		model.addAttribute("vendor", vendorList.get(0));
		model.addAttribute("daichuli", daichuli);
		model.addAttribute("daizhaobiao", daizhaobiao);
		model.addAttribute("daishenhe", daishenhe);
		model.addAttribute("message", message);
		model.addAttribute("user", currentUser);

		return "client/client_index";
	}

	@RequestMapping(value = "/prePipelinePublic", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String prePipelinePublic(
			@ModelAttribute("pipelineItemObj") TPipelineItem pipelineItem,
			Model model) {

		String type = CurrentUserUtils.getRequest().getParameter("type");
		if (StringUtils.isEmpty(type)) {
			type = (String) CurrentUserUtils.getRequest().getAttribute("type");
		}
		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
		TUser currentUser = this.userService.getObject(userDTO.getId());
		List<TVendor> vendorList = this.vendorService.getByProperty("tClient",
				currentUser.gettCompany());
		List<TIndustry> industryList = this.industryService.getAll();
		List<UnitDTO> unitList = this.unitService.getAll();
		Set<TVendor> targetVendorList = new HashSet<TVendor>();
		for (TVendor vendor : vendorList) {
			boolean flag = false;
			for (TVendor tempVendor : targetVendorList) {
				if (tempVendor.gettSupplier().getId() == vendor.gettSupplier()
						.getId()) {
					flag = true;
					break;
				}
			}
			if (!flag) {
				targetVendorList.add(vendor);
			}
		}
		model.addAttribute("vendorList", targetVendorList);
		model.addAttribute("pipelineItemObj", pipelineItem);
		model.addAttribute("industryList", industryList);
		model.addAttribute("unitList", unitList);
		if (type == null) {
			return "client/pipeline_public";
		} else if ("demand".equals(type)) {
			return "client/pipeline_public_demand";
		} else if ("demandlist".equals(type)) {
			String demandId = CurrentUserUtils.getRequest().getParameter(
					"demandId");
			if (demandId == null) {
				demandId = (String) CurrentUserUtils.getRequest().getAttribute(
						"demandId");
			} else {
				CurrentUserUtils.getRequest().setAttribute("demandId",
						Long.parseLong(demandId));
			}
			String pipelineItemId = (String) CurrentUserUtils.getRequest()
					.getAttribute("pipelineItemId");
			List<TDemand> demandList = null;
			List<TPipelineItem> pipelineItems = new ArrayList<TPipelineItem>();

			TDemand demand = null;
			if (StringUtils.isNoneEmpty(demandId)) {
				demand = this.demandService.getObject(Long.parseLong(demandId));
				demandList = this.pipelineHeaderService.getAllDemandByCompany(
						currentUser.gettCompany(), demand);
			} else {
				demandList = this.pipelineHeaderService.getAllDemandByCompany(
						currentUser.gettCompany(), null);
				if (demandList.isEmpty()) {
					return "client/pipeline_public_demand_list";
				}
				demand = demandList.get(0);
				demandList = this.pipelineHeaderService.getAllDemandByCompany(
						currentUser.gettCompany(), demand);
				CurrentUserUtils.getRequest()
						.setAttribute("demandId", demandId);
			}
			pipelineItems = this.pipelineItemService.findByCompanyAndDemand(
					currentUser.gettCompany(), demand);
			model.addAttribute("pipelineItems", pipelineItems);
			model.addAttribute("demandList", demandList);
			model.addAttribute("pipelineItemId", pipelineItemId);
			model.addAttribute("demandObj", demand);
			return "client/pipeline_public_demand_list";
		} else {
			throw new BusinessException();
		}
	}

	/**
	 * c端发布招标信息
	 * 
	 * @param pipelineItemObj
	 * @param result
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/publishPipeline", method = { RequestMethod.POST })
	public String publishPipeline(
			@Valid @ModelAttribute("pipelineItemObj") TPipelineItem pipelineItemObj,
			BindingResult result, Model model, HttpServletRequest request) {

		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
		TUser currentUser = this.userService.getObject(userDTO.getId());
		if (!String.valueOf(UserTypeEnum.CLIENT.getVal()).equals(
				String.valueOf(currentUser.getType()))) {
			logger.error("You are not a client, no permission to access this page!");
			result.addError(new ObjectError("NonEffectiveSupplier",
					"您不是client用户,没有此操作权限!"));
			model.addAttribute("fields", result.getAllErrors());
		}
		// 表单验证
		if (result.hasErrors()) {
			model.addAttribute("formErrors", result.getAllErrors());
			return this.prePipelinePublic(pipelineItemObj, model);
		}
		try {
			request.setAttribute("presentationtime",
					request.getParameter("presentationtime"));
			request.setAttribute("bidopentime",
					request.getParameter("bidopentime"));

			String type = request.getParameter("type");
			TDemand demand = new TDemand();
			if (StringUtils.isNotEmpty(type) && "demand".equals(type)) {
				demand.setCreatedBy(currentUser.getUsername());
				demand.setDelete(false);
				demand.setDemandNo(CommonUtils.generateBizNo(BizType.DEMAND));
				demand.setGmtCreateTime(new Date());
				demand.setGmtUpdateTime(new Date());
				demand.setUpdatedBy(currentUser.getUsername());
				demand = this.demandService.save(demand);
			}
			TPipelineHeader header = new TPipelineHeader();
			header.setCreatedBy(currentUser.getUsername());
			header.setDescription(pipelineItemObj.getBidDescription());
			header.setGmtCreateTime(new Date());
			header.setGmtUpdateTime(new Date());
			header.setIsDelete(0);
			header.settCompany(currentUser.gettCompany());
			header.setUpdatedBy(currentUser.getUsername());
			if (StringUtils.isNotEmpty(type) && "demand".equals(type)) {
				header.settDemand(demand);
			}

			TPipelineItem item = new TPipelineItem();
			item.setAccept(false);
			item.setBidDescription(pipelineItemObj.getBidDescription());
			// item.setBidOpenTime(ConvertTime.StringToDate2(request.getParameter("opentime")));
			item.setBidType(pipelineItemObj.getBidType());
			item.setContactEmail(pipelineItemObj.getContactEmail());
			item.setContactPhone(pipelineItemObj.getContactPhone());
			item.setContactUser(pipelineItemObj.getContactUser());
			item.setGmtCreateTime(new Date());
			item.setGmtUpdateTime(new Date());
			item.setUpdatedBy(currentUser.getUsername());
			item.settPipelineHeader(header);
			// item.setParticipate(false);界面上没有这个
			// item.setPresentationTime(presentationTime); 界面上没有这个
			// 招标
			if (BidTypeEnum.INVITE_BIDS.getVal() == pipelineItemObj
					.getBidType()) {
				if (ConvertTime.isDate1BeforeData2(
						ConvertTime.StringToDate2(request
								.getParameter("presentationtime")), ConvertTime
								.StringToDate2(ConvertTime.getShortTime()))) {
					request.setAttribute("errorMsg", "讲标时间须大于当前时间,请重新输入!");
					return this.prePipelinePublic(pipelineItemObj, model);
				}
				if (ConvertTime.isDate1BeforeData2(ConvertTime
						.StringToDate2(request.getParameter("bidopentime")),
						ConvertTime.StringToDate2(ConvertTime.getShortTime()))) {
					request.setAttribute("errorMsg", "招标截止时间须大于当前时间,请重新输入!");
					return this.prePipelinePublic(pipelineItemObj, model);
				}
				/*
				 * if (ConvertTime.isDate1BeforeOrEqualData2(ConvertTime
				 * .StringToDate2(request.getParameter("bidopentime")),
				 * ConvertTime.StringToDate2(request
				 * .getParameter("presentationtime")))) {
				 * request.setAttribute("errorMsg", "招标截止时间须晚于开标时间,请重新输入!");
				 * return this.prePipelinePublic(pipelineItemObj, model); }
				 */
				item.setBidOpenTime(ConvertTime.StringToDate2(request
						.getParameter("bidopentime")));
				item.setPresentationTime(ConvertTime.StringToDate2(request
						.getParameter("presentationtime")));
				header.gettPipelineItems().add(item);
				this.pipelineHeaderService.save(header);
			}

			// 授予
			if (BidTypeEnum.GRANT.getVal() == pipelineItemObj.getBidType()) {
				String companyID = request.getParameter("companyId");
				if (!StringUtils.isNoneEmpty(companyID)) {
					request.setAttribute("errorMsg", "请选择要授予的公司!");
					return this.prePipelinePublic(pipelineItemObj, model);
				}

				item.setAccept(true);
				header.gettPipelineItems().add(item);
				TPipelineHeader savedPipelineHeader = this.pipelineHeaderService
						.save(header);

				TPipelinePublic pipelinePublic = new TPipelinePublic();
				pipelinePublic.setBidPrice(Long.parseLong(request
						.getParameter("bidPrice")));
				pipelinePublic.setCreatedBy(currentUser.getUsername());
				pipelinePublic.setDelete(false);
				pipelinePublic.setFinalWin(true);
				pipelinePublic.setGmtCreateTime(new Date());
				pipelinePublic.setGmtUpdateTime(new Date());
				pipelinePublic.setSuggestedWin(true);
				pipelinePublic.setCreateContract(false);
				pipelinePublic.settPipelineHeader(header);
				pipelinePublic.settVendor(this.vendorService.getObject(Long
						.parseLong(companyID)));
				pipelinePublic.setUpdatedBy(currentUser.getUsername());
				pipelinePublic.settPipelineHeader(savedPipelineHeader);
				this.pipelinePublicService.save(pipelinePublic);
				logger.debug("saved pipelinePublic success!");
			}
			// 议标
			if (BidTypeEnum.BID_NEGOTIATION.getVal() == pipelineItemObj
					.getBidType()
					|| BidTypeEnum.BID_XUNJIA.getVal() == pipelineItemObj
							.getBidType()) {
				String companyID1 = request.getParameter("companyId1");
				String companyID2 = request.getParameter("companyId2");
				String companyID3 = request.getParameter("companyId3");
				if (!StringUtils.isNoneEmpty(companyID1)
						&& !StringUtils.isNoneEmpty(companyID2)
						&& !StringUtils.isNoneEmpty(companyID3)) {
					request.setAttribute("errorMsg", "请选择要议标的公司!");
					return this.prePipelinePublic(pipelineItemObj, model);
				}
				TPipelinePublic pipelinePublic = null;
				if (StringUtils.isNoneEmpty(companyID1)) {
					header.gettPipelineItems().add(item);
					TPipelineHeader savedPipelineHeader = this.pipelineHeaderService
							.save(header);
					pipelinePublic = new TPipelinePublic();
					// pipelinePublic.setBidPrice(Long.parseLong(request.getParameter("bidPrice")));
					pipelinePublic.setCreatedBy(currentUser.getUsername());
					pipelinePublic.setDelete(false);
					pipelinePublic.setFinalWin(false);
					pipelinePublic.setGmtCreateTime(new Date());
					pipelinePublic.setGmtUpdateTime(new Date());
					pipelinePublic.setSuggestedWin(false);
					pipelinePublic.setCreateContract(false);
					pipelinePublic.settVendor(this.vendorService.getObject(Long
							.parseLong(companyID1)));
					pipelinePublic.setUpdatedBy(currentUser.getUsername());
					pipelinePublic.settPipelineHeader(savedPipelineHeader);
					this.pipelinePublicService.save(pipelinePublic);
					logger.debug("saved pipelinePublic success for company1!");
				}
				if (StringUtils.isNoneEmpty(companyID2)) {
					header.gettPipelineItems().add(item);
					TPipelineHeader savedPipelineHeader = this.pipelineHeaderService
							.save(header);

					pipelinePublic = new TPipelinePublic();
					// pipelinePublic.setBidPrice(Long.parseLong(request.getParameter("bidPrice")));
					pipelinePublic.setCreatedBy(currentUser.getUsername());
					pipelinePublic.setDelete(false);
					pipelinePublic.setFinalWin(false);
					pipelinePublic.setGmtCreateTime(new Date());
					pipelinePublic.setGmtUpdateTime(new Date());
					pipelinePublic.setSuggestedWin(false);
					pipelinePublic.setCreateContract(false);
					pipelinePublic.settVendor(this.vendorService.getObject(Long
							.parseLong(companyID2)));
					pipelinePublic.setUpdatedBy(currentUser.getUsername());
					pipelinePublic.settPipelineHeader(savedPipelineHeader);
					this.pipelinePublicService.save(pipelinePublic);
					logger.debug("saved pipelinePublic success for company2!");
				}
				if (StringUtils.isNoneEmpty(companyID3)) {
					header.gettPipelineItems().add(item);
					TPipelineHeader savedPipelineHeader = this.pipelineHeaderService
							.save(header);

					pipelinePublic = new TPipelinePublic();
					// pipelinePublic.setBidPrice(Long.parseLong(request.getParameter("bidPrice")));
					pipelinePublic.setCreatedBy(currentUser.getUsername());
					pipelinePublic.setDelete(false);
					pipelinePublic.setFinalWin(false);
					pipelinePublic.setGmtCreateTime(new Date());
					pipelinePublic.setGmtUpdateTime(new Date());
					pipelinePublic.setSuggestedWin(false);
					pipelinePublic.setCreateContract(false);
					pipelinePublic.settVendor(this.vendorService.getObject(Long
							.parseLong(companyID3)));
					pipelinePublic.setUpdatedBy(currentUser.getUsername());
					pipelinePublic.settPipelineHeader(savedPipelineHeader);
					this.pipelinePublicService.save(pipelinePublic);
					logger.debug("saved pipelinePublic success for company3!");
				}
			}
			request.setAttribute("errorMsg", "招标信息发布成功!");
			request.removeAttribute("bidopentime");
			request.removeAttribute("presentationtime");
			return "redirect:pipelineList.htm";
		} catch (Exception e) {
			logger.error("client publish pipeline error!", e);
			System.out.println(e.getMessage());
			request.setAttribute("errorMsg", "招标信息发布异常!");
			return this.prePipelinePublic(pipelineItemObj, model);
		}
	}

	/**
	 * c端发布招标信息
	 * 
	 * @param pipelineItemObj
	 * @param result
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/updatePipeline", method = { RequestMethod.POST })
	public String updatePipeline(
			@ModelAttribute("pipelineItemObj") TPipelineItem pipelineItemObj,
			BindingResult result, Model model, HttpServletRequest request) {

		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
		TUser currentUser = this.userService.getObject(userDTO.getId());
		if (!String.valueOf(UserTypeEnum.CLIENT.getVal()).equals(
				String.valueOf(currentUser.getType()))) {
			logger.error("You are not a client, no permission to access this page!");
			result.addError(new ObjectError("NonEffectiveSupplier",
					"您不是client用户,没有此操作权限!"));
			model.addAttribute("fields", result.getAllErrors());
		}
		String demandId = request.getParameter("demandId");
		boolean validationPassed = false;
		// 表单验证
		if (StringUtils.isEmpty(request.getParameter("bidDescription"))) {
			request.setAttribute("errorMsg", "描述信息为空!");
			validationPassed = false;
		} else if (StringUtils.isEmpty(request.getParameter("contactUser"))) {
			request.setAttribute("errorMsg", "联系人为空!");
			validationPassed = false;
		} else if (StringUtils.isEmpty(request.getParameter("contactPhone"))) {
			request.setAttribute("errorMsg", "联系人电话为空!");
			validationPassed = false;
		} else if (StringUtils.isEmpty(request.getParameter("contactEmail"))) {
			request.setAttribute("errorMsg", "联系人邮箱为空!");
			validationPassed = false;
		} else {
			validationPassed = true;
		}
		if (validationPassed == false) {
			request.setAttribute("type", "demandlist");
			request.setAttribute("demandId", demandId);
			return this.prePipelinePublic(pipelineItemObj, model);
		}
		try {
			request.setAttribute("presentationtime",
					request.getParameter("presentationtime"));
			request.setAttribute("bidopentime",
					request.getParameter("bidopentime"));

			String type = request.getParameter("type");
			if (StringUtils.isNotEmpty(type) && !"demandlist".equals(type)) {
				throw new BusinessException("No demandID found!");
			}
			String pipelineItemId = request.getParameter("pipelineItemId");
			TPipelineItem item = this.pipelineItemService.getObject(Long
					.parseLong(pipelineItemId));

			TPipelineHeader header = item.gettPipelineHeader();
			header.setDescription(request.getParameter("bidDescription"));
			header.setGmtUpdateTime(new Date());
			header.setUpdatedBy(currentUser.getUsername());

			item.setBidDescription(request.getParameter("bidDescription"));
			item.setContactEmail(request.getParameter("contactEmail"));
			item.setContactPhone(request.getParameter("contactPhone"));
			item.setContactUser(request.getParameter("contactUser"));
			item.setGmtUpdateTime(new Date());
			item.setUpdatedBy(currentUser.getUsername());
			// item.setParticipate(false);界面上没有这个
			// item.setPresentationTime(presentationTime); 界面上没有这个
			// 招标
			String bidType = request.getParameter("bidType");
			if (String.valueOf(BidTypeEnum.INVITE_BIDS.getVal())
					.equals(bidType)) {
				if (ConvertTime.isDate1BeforeData2(
						ConvertTime.StringToDate2(request
								.getParameter("presentationtime")), ConvertTime
								.StringToDate2(ConvertTime.getShortTime()))) {
					request.setAttribute("errorMsg", "讲标时间须大于当前时间,请重新输入!");
					return this.prePipelinePublic(pipelineItemObj, model);
				}
				if (ConvertTime.isDate1BeforeData2(ConvertTime
						.StringToDate2(request.getParameter("bidopentime")),
						ConvertTime.StringToDate2(ConvertTime.getShortTime()))) {
					request.setAttribute("errorMsg", "招标截止时间须大于当前时间,请重新输入!");
					return this.prePipelinePublic(pipelineItemObj, model);
				}
				/*
				 * if (ConvertTime.isDate1BeforeOrEqualData2(ConvertTime
				 * .StringToDate2(request.getParameter("bidopentime")),
				 * ConvertTime.StringToDate2(request
				 * .getParameter("presentationtime")))) {
				 * request.setAttribute("errorMsg", "招标截止时间须晚于开标时间,请重新输入!");
				 * return this.prePipelinePublic(pipelineItemObj, model); }
				 */
				item.setBidOpenTime(ConvertTime.StringToDate2(request
						.getParameter("bidopentime")));
				item.setPresentationTime(ConvertTime.StringToDate2(request
						.getParameter("presentationtime")));
				this.pipelineHeaderService.save(header);
			}

			// 授予
			if (String.valueOf(BidTypeEnum.GRANT.getVal()).equals(bidType)) {
				String companyID = request.getParameter("companyId");
				if (!StringUtils.isNoneEmpty(companyID)) {
					request.setAttribute("errorMsg", "请选择要授予的公司!");
					return this.prePipelinePublic(pipelineItemObj, model);
				}
				if (header.gettPipelinePublics().size() == 0) {
					throw new BusinessException(
							"No pipelinePublic find for BidType[Shouyu].");
				}
				TPipelinePublic pipelinePublic = new ArrayList<TPipelinePublic>(
						header.gettPipelinePublics()).get(0);
				pipelinePublic.setBidPrice(Long.parseLong(request
						.getParameter("bidPrice")));
				pipelinePublic.setFinalWin(true);
				pipelinePublic.setGmtUpdateTime(new Date());
				pipelinePublic.setSuggestedWin(true);
				pipelinePublic.setUpdatedBy(currentUser.getUsername());
				this.pipelinePublicService.save(pipelinePublic);
				this.pipelineHeaderService.save(header);
				logger.debug("updated pipelinePublic success!");
			}
			// 议标
			if (String.valueOf(BidTypeEnum.BID_NEGOTIATION.getVal()).equals(
					bidType)
					|| String.valueOf(BidTypeEnum.BID_XUNJIA.getVal()).equals(
							bidType)) {
				Set<TPipelinePublic> pipelinePublics = header
						.gettPipelinePublics();
				for (TPipelinePublic pipelinePublic : pipelinePublics) {
					pipelinePublic.setGmtUpdateTime(new Date());
					pipelinePublic.setUpdatedBy(currentUser.getUsername());
					if (StringUtils
							.isNotEmpty(request.getParameter("bidPrice"))) {
						pipelinePublic.setBidPrice(Long.parseLong(request
								.getParameter("bidPrice")));
					}
					this.pipelinePublicService.save(pipelinePublic);
				}
				this.pipelineHeaderService.save(header);
			}
			request.setAttribute("errorMsg", "修改成功!");
			request.removeAttribute("bidopentime");
			request.removeAttribute("presentationtime");
			return this.prePipelinePublic(pipelineItemObj, model);
		} catch (Exception e) {
			logger.error("client publish pipeline error!", e);
			System.out.println(e.getMessage());
			request.setAttribute("errorMsg", "招标信息发布异常!");
			return this.prePipelinePublic(pipelineItemObj, model);
		}
	}

	/**
	 * c端处理招标信息
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/pipelineList", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String pipelineList(Model model, HttpServletRequest request) {

		// 处理招标信息
		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
		TUser currentUser = this.userService.getObject(userDTO.getId());
		List<TPipelineItem> pipelineItems = this.pipelineItemService
				.findByCompany(new TCompany[] { currentUser.gettCompany() });
		model.addAttribute("pipelineItems", pipelineItems);
		model.addAttribute("purchaseOrderId",
				StringUtils.trimToNull(request.getParameter("purchaseOrderID")));

		return "client/pipeline_list";
	}

	@RequestMapping(value = "/supplierList", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String supplierList(Model model, HttpServletRequest request) {

		// TODO T_purchase_order
		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
		TUser currentUser = this.userService.getObject(userDTO.getId());
		
//		 List<TVendor> vendorList = null  ;
//		 if(currentUser.gettCompany().getGroupId()!=null&&!currentUser.gettCompany().getGroupId().equals("")){
//			 TCompany groupCompany = this.companyService.getObject(currentUser.gettCompany().getGroupId());
//			 vendorList = this.vendorService.getByProperty("tClient",  groupCompany);
//		 }else{
//		   vendorList = this.vendorService.getByProperty("tClient",  currentUser.gettCompany());
//		 }
//		 
//		 List<TPurchaseOrder> oderAll = new ArrayList<TPurchaseOrder>();
//		 
//		 for (int i = 0  ; i < vendorList.size() ; i++){
//			 TVendor vendor = vendorList.get(i);
//				List<TPurchaseOrder> tPurchaseOrder = this.purchaseOrderService
//						.getByProperty("tVendor", vendor);
//				for(int j = 0; j<tPurchaseOrder.size();j++){
//					oderAll.add(tPurchaseOrder.get(j));
//				}
//			 
//		 }
//		
//		allPurchaseOrder = oderAll;
//		model.addAttribute("purchaseOrderList", oderAll);
		
		List<TCompany> companys = this.companyService.getByProperty("groupId", currentUser.getId());
		 List<TVendor> vendorList = this.vendorService.getAll();
		 System.out.println(vendorList.get(0).gettPurchaseOrder().get(0).gettVendor().getVendorName());
//		 if(currentUser.gettCompany().getGroupId()!=null&&!currentUser.gettCompany().getGroupId().equals("")){
//			 TCompany groupCompany = this.companyService.getObject(currentUser.gettCompany().getGroupId());
//			 vendorList = this.vendorService.getByProperty("tClient",  groupCompany);
//		 }else{
//		   vendorList = this.vendorService.getByProperty("tClient",  currentUser.gettCompany());
//		 }
		
//		List<TVendor> vendors = new ArrayList<TVendor>();
//		for (int i = 0; i < oderAll.size(); i++) {
//			//companys.add(oderAll.get(i).gettCompany());
//			vendors.add(oderAll.get(i).gettVendor());
//		}
		model.addAttribute("companys", companys);
		model.addAttribute("vendors", vendorList);

		return "client/supplier_list";
	}

	List<TPurchaseOrder> allPurchaseOrder = new ArrayList<TPurchaseOrder>();

	@SuppressWarnings("unused")
	@RequestMapping(value = "/nextPreSupplierAudit", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String nextPreSupplierAudit(Model model, HttpServletRequest request) {

		// TODO
		String orderPurchaseOrderID = request.getParameter("purchaseOrderID");
		long purchaseOrderID = 0;
		for (int i = 0; i < allPurchaseOrder.size(); i++) {
			long chackID = allPurchaseOrder.get(i).getId();
			if (chackID == Long.parseLong(orderPurchaseOrderID)
					&& i != (allPurchaseOrder.size() - 1)) {
				purchaseOrderID = allPurchaseOrder.get(i + 1).getId();
				break;
			} else {
				UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
				TUser currentUser = this.userService.getObject(userDTO.getId());
				List<TPurchaseOrder> tPurchaseOrder = this.purchaseOrderService
						.getByProperty("tCompany", currentUser.gettCompany());
				allPurchaseOrder = tPurchaseOrder;
				model.addAttribute("purchaseOrderList", tPurchaseOrder);
				List<TCompany> companys = new ArrayList<TCompany>();
				List<TVendor> vendors = new ArrayList<TVendor>();
				for (int j = 0; j < tPurchaseOrder.size(); j++) {
					companys.add(tPurchaseOrder.get(j).gettCompany());
					vendors.add(tPurchaseOrder.get(j).gettVendor());
				}
				model.addAttribute("companys", companys);
				model.addAttribute("vendors", vendors);
				return "client/supplier_list";
			}

		}

		TPurchaseOrder purchaseOrder = this.purchaseOrderService
				.getObject(purchaseOrderID);
		TVendor vendor = purchaseOrder.gettVendor();

		model.addAttribute("purchaseOrder", purchaseOrder);
		model.addAttribute("vendor", vendor);

		return "client/supplier_audit";
	}

	@RequestMapping(value = "/preSupplierAudit", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String preSupplierAudit(Model model, HttpServletRequest request) {

		// TODO
		String purchaseOrderID = request.getParameter("purchaseOrderID");
		
		String checkBoxPage=request.getParameter("selectCount");
		//当前页码
		String currentPage=request.getParameter("currentPage");

		String[] idTemp =null;
		if(checkBoxPage!=null)
		{
			idTemp = checkBoxPage.split(",");
		}
		
		//前一页
		if(currentPage.equals("prev"))
		{
			int tempIndex=0;
			for(int i=0;i<idTemp.length;i++)
			{
				if(purchaseOrderID.equals(idTemp[i]))
				{	
					tempIndex=i;				
				}
			}
			if(tempIndex==0)
			{
				return supplierList(model,request);
			}
			purchaseOrderID=idTemp[tempIndex-1];
		}
		else if(currentPage.equals("next"))//后一页
		{
			int tempIndex=0;
			for(int i=0;i<idTemp.length;i++)
			{
				if(purchaseOrderID.equals(idTemp[i]))
				{	
					tempIndex=i;				
				}
			}
			if(tempIndex==(idTemp.length-1))
			{
				return supplierList(model,request);
			}
			purchaseOrderID=idTemp[tempIndex+1];
		}
		
		TPurchaseOrder purchaseOrder = this.purchaseOrderService.getObject(Long
				.parseLong(purchaseOrderID));
		TVendor vendor = purchaseOrder.gettVendor();
		
		List<PageDTO> pageList=new ArrayList<PageDTO>();
		if(idTemp!=null)
		{
			for(int i=0;i<idTemp.length;i++)
			{
				if(!"".equals(idTemp[i]))
				{	
					PageDTO page=new PageDTO();
					page.setCurrentIndex(i);
					page.setOrderID(Integer.parseInt(idTemp[i]));
					if(idTemp[i].equals(purchaseOrderID))
					{
						page.setCurrentPageSelected(true);
					}
					pageList.add(page);
				}
			}
		}
		
		model.addAttribute("purchaseOrder", purchaseOrder);
		model.addAttribute("vendor", vendor);
		model.addAttribute("pageList",pageList);
		model.addAttribute("currentPage",currentPage);
		model.addAttribute("selectCount",checkBoxPage);
		
		return "client/supplier_audit";
	}

	/**
	 * 
	 * author wangjunxi
	 * 
	 * @return
	 */
	@RequestMapping(value = "/purchaseOrderList", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String purchaseOrderList(Model model, HttpServletRequest request) {

		String orderStatusStr=request.getParameter("orderStatus");
		Short orderStatus=5;
		if(orderStatusStr!=null)
		{
			orderStatus =Short.parseShort(request.getParameter("orderStatus"));
		}	
		// TODO
		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
		TUser currentUser = this.userService.getObject(userDTO.getId());

		 List<TVendor> vendorList =
		 this.vendorService.getByProperty("tClient",
		 currentUser.gettCompany());
		 TVendor vendor = vendorList.get(0);
		List<TPurchaseOrder> tPurchaseOrder = this.purchaseOrderService
				.getByPropertyByStatus("tVendor", vendor, orderStatus);// (vendor.gettClient());
		//milestone_type状态暂存字段
		for(int i=0 ; i<tPurchaseOrder.size();i++){
			Set<TPurchaseOrderPayment> oldtPurchaseOrderPaymentSet = tPurchaseOrder.get(i).gettPurchaseOrderPayment();
			List<TPurchaseOrderPayment> oldtPurchaseOrderPaymentList = new ArrayList<TPurchaseOrderPayment>(oldtPurchaseOrderPaymentSet);
			List<TPurchaseOrderPayment> tPurchaseOrderPaymentList = new ArrayList<TPurchaseOrderPayment>();
			for(int j = 0 ; j <oldtPurchaseOrderPaymentList.size() ; j++){
				TPurchaseOrderPayment oldtPurchaseOrderPayment = oldtPurchaseOrderPaymentList.get(j);
			    Integer	deliveryNote1 = isNull(oldtPurchaseOrderPayment.getDeliveryNote1());
			    Integer deliveryNoteAttachmentStatus1 = isNull(oldtPurchaseOrderPayment.getDeliveryNoteAttachmentStatus1());
			    Integer acceptanceReportAttachmentStatus = isNull(oldtPurchaseOrderPayment.getAcceptanceReportAttachmentStatus());
			    Integer invoiceAttachmentStatus1  = isNull(oldtPurchaseOrderPayment.getInvoiceAttachmentStatus1());
			    Long paidAmount = oldtPurchaseOrderPayment.getPaidAmount();
			    Long billedAmount =  oldtPurchaseOrderPayment.getBilledAmount();
			    //待发货  所有字段=0
			    if(deliveryNote1== 0 &&deliveryNoteAttachmentStatus1==0 && acceptanceReportAttachmentStatus==0 
			    		&&invoiceAttachmentStatus1 == 0 ){
			    	oldtPurchaseOrderPayment.setMilestoneType((short)1);
			    }
			    //已发货   delivery_note_1=1；其他字段=0
			     if (deliveryNote1==1&&deliveryNoteAttachmentStatus1==0 && acceptanceReportAttachmentStatus==0 
			    		&&invoiceAttachmentStatus1 == 0 && (paidAmount==null||paidAmount==0)
			    		&& (billedAmount==null||billedAmount==0)){
			    	oldtPurchaseOrderPayment.setMilestoneType((short)2);
			    }
			    //已验货  delivery_note_1=1 and delivery_note_attachment_status_1=1 且其他字段等于0
			     if(deliveryNote1==1&&deliveryNoteAttachmentStatus1==1 && acceptanceReportAttachmentStatus==0 
			    		&&invoiceAttachmentStatus1 == 0 && (paidAmount==null||paidAmount==0)
			    		&& (billedAmount==null||billedAmount==0)){
			    	oldtPurchaseOrderPayment.setMilestoneType((short)3);
			    }
			    //已验收  acceptance_report_attachment_status=1 且 invoice_attachment_status_1=0
			     if (acceptanceReportAttachmentStatus==1  &&invoiceAttachmentStatus1 == 0 ){
			    	oldtPurchaseOrderPayment.setMilestoneType((short)4);
			    }
			    //已收发票 invoice_attachment_status_1=1 且 paid amount<billed amount
			     if (invoiceAttachmentStatus1==1 && (paidAmount<billedAmount)){
			    	oldtPurchaseOrderPayment.setMilestoneType((short)5);
			    }
			    //已付款  paid amount = billed amount
			     if (paidAmount!=0&&billedAmount!=0&&paidAmount==billedAmount){
			    	oldtPurchaseOrderPayment.setMilestoneType((short)6);
			    }
			     tPurchaseOrderPaymentList.add(oldtPurchaseOrderPayment);
			     
			}
			
			Set<TPurchaseOrderPayment> set = new HashSet<TPurchaseOrderPayment>(tPurchaseOrderPaymentList);
			tPurchaseOrder.get(i).settPurchaseOrderPayment(set);
			
		}
		
		model.addAttribute("purchaseOrderList", tPurchaseOrder);
		// 查找列表的状态
		model.addAttribute("orderStatus",orderStatus);
		return "client/purchase_order_list";
	}
	public Integer isNull (Integer value){
		if(value==null||value.equals("")||value==0){
			return 0;
		}else{
			return value;
		}
	}
	
	@RequestMapping(value = "/estimate", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String estimate(Model model, HttpServletRequest request) {

		// TODO
		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
		TUser currentUser = this.userService.getObject(userDTO.getId());

		 List<TVendor> vendorList =this.vendorService.getByProperty("tClient",currentUser.gettCompany());
		 Integer thisCompanyScore =  0 ;
		 Integer mingCi =  1 ;
		 for(int i= 0 ;i<vendorList.size();i++){
			 TVendor vendor = vendorList.get(i);
			 for (int j = 0 ; j<vendor.gettVendorHistory().size(); j++){
				 thisCompanyScore = thisCompanyScore+ vendor.gettVendorHistory().get(j).getEvaluationScore();
			 }
			 
		 }
		
		 List<TVendor> vendorListAll = this.vendorService.getAll();
		 
		 for (int i = 0 ; i<vendorListAll.size() ; i++){
			 TVendor vendorOnly = vendorListAll.get(i);
			 List<TVendorHistory> vendorHistoryOnly = vendorOnly.gettVendorHistory();
			 Integer otherCompanyScore = 0 ;
				 for(int j=0 ;j<vendorHistoryOnly.size();j++){
					 otherCompanyScore = otherCompanyScore +vendorHistoryOnly.get(j).getEvaluationScore();
				 }
		     
			if(otherCompanyScore>thisCompanyScore){
				mingCi= mingCi+1;
			}
			 
		 }
		 
		 Integer scoreEvl  = 0 ;
		 Integer gradeEvl  = 0 ;
		 
		 if(vendorList.size()!=0){
			 scoreEvl = thisCompanyScore / (vendorList.size());
		 }
		 List<TCompany> comPanyAll = this.companyService.getByProperty("businessType", (short)1);
		 gradeEvl = mingCi / comPanyAll.size(); 
		
		TCompany company;
		long companyID = userDTO.gettCompany().getId();
		String vendorID = request.getParameter("vendorID");
//		if (vendorcompanyID != null) {
//			company = this.companyService.getObject(Long
//					.parseLong(vendorcompanyID));
//		} else {
//			company = this.companyService.getObject(companyID);
//		}
		TVendor vendor=new TVendor();
		vendor.setId(Long.parseLong(vendorID));
		List<TPurchaseOrder> purchaseOrderList = this.purchaseOrderService
				.getByProperty("tVendor", vendor);
		
		model.addAttribute("scoreEvl", scoreEvl);
		model.addAttribute("gradeEvl", gradeEvl);
		model.addAttribute("purchaseOrderList", purchaseOrderList);
		model.addAttribute("vendorID",vendorID);

		return "client/estimate";
	}

	@RequestMapping(value = "/preCreateContract", method = RequestMethod.GET)
	public String preCreateContract(
			@ModelAttribute("pipelineId") String pipelineId, Model model) {

		if (!NumberUtils.isDigits(pipelineId)) {
			throw new BusinessException(String.format(
					"pipelineId %s is illegal. ", pipelineId));
		}
		// 中标记录
		TPipelinePublic pipelinePublic = pipelinePublicService
				.getPipelinePublicByPipelineIdAndWinflag(
						Long.parseLong(pipelineId), true, true);
		if (null == pipelinePublic) {
			throw new BusinessException("no supplie win the pipeline. ");
		}
		// 省列表
		List<TProvince> pList = provinceService.getAll();
		// 采购组织列表
		List<PurchaseOrganizationDTO> purchaseOrgList = purchaseOrganizationService
				.getByCompany(CurrentUserUtils.getInstance().getUser()
						.gettCompany());
		// 獲取有效的子公司列表
		List<CompanyDTO> companyList = companyService
				.findSubCompanyList(CurrentUserUtils.getInstance().getUser()
						.gettCompany());
		model.addAttribute(
				"purchaseOrder",
				new PurchaseOrderDTO(CommonUtils
						.generateBizNo(BizType.PURCHASE_ORDER)));
		model.addAttribute("pipelinePublic", pipelinePublic);
		model.addAttribute("pList", pList);
		model.addAttribute("purchaseOrgList", purchaseOrgList);
		model.addAttribute("currencyTypeList", CurrencyTypeEnum.values());
		model.addAttribute("companyList", companyList);
		return "client/create_contract";
	}

	@RequestMapping(value = "/createContract", method = RequestMethod.POST)
	public String createContract(
			@ModelAttribute("purchaseOrder") PurchaseOrderDTO purchaseOrder,
			@ModelAttribute("submitType") Integer submitType,
			RedirectAttributes rAttr) {

		//
		PurchaseOrderDTO purchaseOrderDTO = purchaseOrderService
				.save(purchaseOrder);
		//
		// rAttr.addFlashAttribute("purchaseOrderID", purchaseOrderDTO.getId());
		if (submitType == 1) {
			return "redirect:../client/pipelineList.htm?purchaseOrderID="
					+ purchaseOrderDTO.getId();
		} else {
			return "redirect:../client/preCreateOrder.htm?purchaseOrderID="
					+ purchaseOrderDTO.getId();
		}
	}

	@RequestMapping(value = "/preCreateOrder", method = RequestMethod.GET)
	public String preCreateOrder(Model model, HttpServletRequest request) {

		String tempPurchaseOrderId = StringUtils.trimToEmpty(request
				.getParameter("purchaseOrderID"));
		Long purchaseOrderId = 0L;
		if (tempPurchaseOrderId == null || tempPurchaseOrderId.isEmpty()) {
			String msg = "PurchaseOrderId is null. ";
			logger.error(msg);
			throw new BusinessException(msg);
		} else {
			purchaseOrderId = Long.parseLong(tempPurchaseOrderId);
		}

		if (purchaseOrderId == null || purchaseOrderId <= 0) {
			String msg = String.format("PurchaseOrderId[%s] is illegal. ",
					purchaseOrderId);
			logger.error(msg);
			throw new BusinessException(msg);
		}
		// check
		int cnt = purchaseOrderPaymentService
				.countByPurchaseOrderId(purchaseOrderId);
		if (cnt > 0) {
			String msg = String
					.format("PurchaseOrderPayment is already created. PurchaseOrderId[%s]",
							purchaseOrderId);
			logger.error(msg);
			throw new BusinessException(msg);
		}
		// 单位列表
		List<UnitDTO> unitList = unitService.getAll();
		// 物料列表
		List<TMaterialMasterClient> materialList = materialMasterClientService
				.getListByCompany(CurrentUserUtils.getInstance().getUser()
						.gettCompany());
		//
		model.addAttribute("unitList", unitList);
		model.addAttribute("purchaseOrderId", purchaseOrderId);
		model.addAttribute("currency",
				purchaseOrderService.getCurrencyByOrderId(purchaseOrderId));
		model.addAttribute("price",
				purchaseOrderService.getPriceByOrderId(purchaseOrderId));
		model.addAttribute("materialList", materialList);
		return "client/create_order";
	}

	@RequestMapping(value = "/createOrder", method = RequestMethod.POST)
	@ResponseBody
	public String createOrder(
			@RequestBody List<PurchaseOrderPaymentDTO> orderPaymentDTOList) {

		try {
			if (CollectionUtils.isEmpty(orderPaymentDTOList)) {
				logger.error("orderPaymentDTOList's size is 0. ");
				throw new BusinessException("orderPaymentDTOList's size is 0. ");
			}
			PurchaseOrderPaymentDTO purchaseOrderPayment = orderPaymentDTOList
					.get(0);
			if (null != purchaseOrderPayment.getId()
					&& purchaseOrderPayment.getId() > 0) {
				// update PurchaseOrderPayment
				purchaseOrderPayment = purchaseOrderPaymentService
						.update(purchaseOrderPayment);
			} else {
				// add PurchaseOrderPayment
				purchaseOrderPayment = purchaseOrderPaymentService
						.save(purchaseOrderPayment);
			}
			//
			return JsonUtil
					.serialize(new CommonResponseDto<PurchaseOrderPaymentDTO>(
							RetCodeEnum.SUCCESS.getCode(), RetCodeEnum.SUCCESS
									.getMsg(), purchaseOrderPayment));
		} catch (Exception e) {
			logger.error("updatePurchaseOrderPayment occurs exception. ", e);
			if (e instanceof DuplicateObjectException) {
				return JsonUtil.serialize(new CommonResponseDto<String>(
						RetCodeEnum.PURCHASE_ORDER_PAYMENT_REPEAT.getCode(),
						RetCodeEnum.PURCHASE_ORDER_PAYMENT_REPEAT.getMsg()));
			}
			if (e instanceof AmountExceedLimitException) {
				return JsonUtil.serialize(new CommonResponseDto<String>(
						RetCodeEnum.TOTAL_PLAN_AMOUNT_EXCEED_ORDER_PRICE
								.getCode(),
						RetCodeEnum.TOTAL_PLAN_AMOUNT_EXCEED_ORDER_PRICE
								.getMsg()));
			} else {
				return JsonUtil.serialize(new CommonResponseDto<String>(
						RetCodeEnum.FAIL.getCode(), e.getMessage()));
			}
		}
	}

	@RequestMapping(value = "/getPurchaseOrderPayment", method = {
			RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public String getPurchaseOrderPayment(
			@ModelAttribute("orderPaymentId") String orderPaymentId) {

		//
		try {
			if (StringUtils.isBlank(orderPaymentId)) {
				throw new BusinessException("orderPaymentId is null. ");
			}
			TPurchaseOrderPayment purchaseOrderPayment = purchaseOrderPaymentService
					.getObject(Long.parseLong(orderPaymentId));
			return JsonUtil
					.serialize(new CommonResponseDto<TPurchaseOrderPayment>(
							RetCodeEnum.SUCCESS.getCode(), RetCodeEnum.SUCCESS
									.getMsg(), purchaseOrderPayment));
		} catch (Exception e) {
			logger.error("getPurchaseOrderPayment occurs exception. ", e);
			return JsonUtil.serialize(new CommonResponseDto<String>(
					RetCodeEnum.FAIL.getCode(), e.getMessage()));
		}
	}

	@RequestMapping(value = "/addClientMaterial", method = RequestMethod.POST)
	@ResponseBody
	public String addClientMaterial(
			@RequestBody MaterialMasterClientDTO materialMasterClientDTO) {

		try {
			if (null == materialMasterClientDTO) {
				throw new NullObjectException(
						"MaterialMasterClientDTO is null. ");
			}
			materialMasterClientDTO = materialMasterClientService
					.addMaterialMasterClient(materialMasterClientDTO);
			if (null == materialMasterClientDTO
					|| materialMasterClientDTO.getId() == null
					|| materialMasterClientDTO.getId() <= 0) {
				throw new BusinessException("Add client material failed. ");
			} else {
				return JsonUtil
						.serialize(new CommonResponseDto<MaterialMasterClientDTO>(
								RetCodeEnum.SUCCESS.getCode(),
								RetCodeEnum.SUCCESS.getMsg(),
								materialMasterClientDTO));
			}
		} catch (Exception e) {
			logger.error("add material occurs exception. ", e);
			if (e instanceof DuplicateObjectException) {
				return JsonUtil.serialize(new CommonResponseDto<>(
						RetCodeEnum.MATERIAL_NAME_REPEAT.getCode(),
						RetCodeEnum.MATERIAL_NAME_REPEAT.getMsg()));
			} else {
				return JsonUtil.serialize(new CommonResponseDto<>(
						RetCodeEnum.FAIL.getCode(), e.getMessage()));
			}
		}
	}

	@RequestMapping(value = "/addPurchaseOrderItems", method = RequestMethod.POST)
	@ResponseBody
	public String addPurchaseOrderItems(
			@RequestBody List<PurchaseOrderItemsDTO> purchaseOrderItemsList) {

		try {
			purchaseOrderItemsService
					.addPurchaseOrderItems(purchaseOrderItemsList);
			return JsonUtil
					.serialize(new CommonResponseDto<>(RetCodeEnum.SUCCESS
							.getCode(), RetCodeEnum.SUCCESS.getMsg()));
		} catch (Exception e) {
			logger.error("add purchase order items occurs exception. ", e);
			if (e instanceof SubmitZeroItemsException) {
				return JsonUtil.serialize(new CommonResponseDto<>(
						RetCodeEnum.SUBMIT_ZERO_ITEMS.getCode(),
						RetCodeEnum.SUBMIT_ZERO_ITEMS.getMsg()));
			} else if (e instanceof DuplicateObjectException) {
				return JsonUtil.serialize(new CommonResponseDto<>(
						RetCodeEnum.ORDER_ITEM_REPEAT.getCode(),
						RetCodeEnum.ORDER_ITEM_REPEAT.getMsg()));
			} else {
				return JsonUtil.serialize(new CommonResponseDto<>(
						RetCodeEnum.SYSTEM_EXCEPTION.getCode(),
						RetCodeEnum.SYSTEM_EXCEPTION.getMsg()));
			}
		}
	}

	@RequestMapping(value = "/getPurchaseOrganizationUser", method = {
			RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String getPurchaseOrganizationUser(
			@ModelAttribute("purchaseOrganizationId") String purchaseOrganizationId) {

		//
		try {
			if (StringUtils.isBlank(purchaseOrganizationId)) {
				throw new BusinessException("purchaseOrganizationId is null. ");
			}
			List<TPurchaseOrganizationUser> list = purchaseOrganizationUserService
					.getListByPurchaseOrganizationId(
							Long.parseLong(purchaseOrganizationId),
							Constants.USEFULL);
			return JsonUtil
					.serialize(new CommonResponseDto<List<TPurchaseOrganizationUser>>(
							RetCodeEnum.SUCCESS.getCode(), RetCodeEnum.SUCCESS
									.getMsg(), list));
		} catch (Exception e) {
			logger.error("getPurchaseOrganizationUser occurs exception. ", e);
			return JsonUtil.serialize(new CommonResponseDto<String>(
					RetCodeEnum.FAIL.getCode(), e.getMessage()));
		}
	}

	@RequestMapping(value = "/preEditOrder", method = RequestMethod.GET)
	public String preEditOrder(
			@ModelAttribute("purchaseOrderId") Long purchaseOrderId, Model model) {

		PurchaseOrderDTO purchaseOrderDTO = new PurchaseOrderDTO();
		purchaseOrderDTO.setId(purchaseOrderId);
		// 里程碑列表
		List<PurchaseOrderPaymentDTO> purchaseOrderPaymentList = purchaseOrderPaymentService
				.getByPurchaseOrder(purchaseOrderDTO);
		// 订单信息列表
		List<TPurchaseOrderItems> purchaseOrderItemList = purchaseOrderItemsService
				.getByPurchaseOrderDTO(purchaseOrderDTO);
		// 单位列表
		List<UnitDTO> unitList = unitService.getAll();
		//
		model.addAttribute("purchaseOrderPaymentList", purchaseOrderPaymentList);
		model.addAttribute("purchaseOrderItemList", purchaseOrderItemList);
		model.addAttribute("unitList", unitList);
		model.addAttribute("purchaseOrderId", purchaseOrderId);
		return "client/edit_order";
	}

	@RequestMapping(value = "/prePipelineResult", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String prePipelineResult(
			@ModelAttribute("pipelineId") String pipelineId, Model model) {

		if (!NumberUtils.isDigits(pipelineId)) {
			throw new BusinessException(String.format(
					"pipelineId %s is illegal. ", pipelineId));
		}
		//
		PipelineItemDTO pipelineItem = pipelineItemService
				.getPipelineItemByHeaderId(Long.parseLong(pipelineId));
		model.addAttribute("pipelineItem", pipelineItem);
		//
		List<PipelinePublicDTO> pipelinePublicList = pipelinePublicService
				.getPipelinePublicListByPipelineId(Long.parseLong(pipelineId));
		model.addAttribute("pipelinePublicList", pipelinePublicList);
		return "client/pipeline_result";
	}

	@SuppressWarnings({ "rawtypes", "unused" })
	@RequestMapping(value = "/pipelineResult", method = RequestMethod.POST)
	@ResponseBody
	public String pipelineResult(
			@RequestBody List<PipelinePublicDTO> pipelinePublicList) {

		int rt = pipelinePublicService.updatePipelinePublic(pipelinePublicList);
		return JsonUtil.serialize(new CommonResponseDto(RetCodeEnum.SUCCESS
				.getCode(), RetCodeEnum.SUCCESS.getMsg()));
	}

	@RequestMapping(value = "/preConfirmOrder", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String preConfirmOrder(Model model, HttpServletRequest request) {

		Long purchaseOrderId = Long.parseLong(request
				.getParameter("purchaseOrderID"));

		TPurchaseOrder purchaseOrder = this.purchaseOrderService
				.getObject(purchaseOrderId);
		model.addAttribute("purchaseOrder", purchaseOrder);

		// Set<TSalesOrderItems> tSalesOrderItems =
		// salesOrder.gettSalesOrderItems();
		// List<TSalesOrderItems> tSalesOrderItemsList = new
		// ArrayList<TSalesOrderItems>(tSalesOrderItems);
		// model.addAttribute("salesOrderItems", tSalesOrderItemsList);

		return "client/confirm_order";
	}

	@SuppressWarnings({ "rawtypes" })
	@RequestMapping(value = "/confirmOrder", method = { RequestMethod.GET,
			RequestMethod.POST })
	@ResponseBody
	public String ConfirmOrder(
			@RequestBody List<PurchaseOrderExecutionItemsDTO> purchaseOrderExecutionItems,
			HttpServletRequest request) {

		try {
			String sourceStrs = request.getParameter("orderExecutionId");
			// purchaseOrderExecution的ID
			String[] orderExecutions = sourceStrs.split(",");
			// 更新purchaseOrderExecution等相关表的数据
			purchaseOrderExecutionService.confirmPurchaseOrderExecution(
					orderExecutions, purchaseOrderExecutionItems);

			return JsonUtil.serialize(new CommonResponseDto(RetCodeEnum.SUCCESS
					.getCode(), RetCodeEnum.SUCCESS.getMsg()));
		} catch (Exception e) {
			return JsonUtil.serialize(new CommonResponseDto<String>(
					RetCodeEnum.FAIL.getCode(), e.getMessage()));
		}
	}

	@RequestMapping(value = "/preConfirmInvoice", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String preConfirmInvoice(Model model, HttpServletRequest request) {

		// TODO
		// 查询salesOrder表
		String purchaseOrderID = request.getParameter("purchaseOrderID");
		List<TPurchaseOrder> purchaseOrders = this.purchaseOrderService
				.getByProperty("id", Long.parseLong(purchaseOrderID));
		TPurchaseOrder purchaseOrder = purchaseOrders.get(0);
		Set<TPurchaseOrderPayment> tPurchaseOrderPayment = purchaseOrder
				.gettPurchaseOrderPayment();

		List<TPurchaseOrderPayment> tPurchaseOrderPaymentList = new ArrayList<TPurchaseOrderPayment>(
				tPurchaseOrderPayment);
		model.addAttribute("tSalesOrderPayment", new TSalesOrderPayment());
		model.addAttribute("purchaseOrder", purchaseOrder);
		model.addAttribute("tPurchaseOrderPayment", tPurchaseOrderPaymentList);
		return "client/confirm_invoice";
	}

	@RequestMapping(value = "/preOrderEstimate", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String preOrderEstimate(Model model, HttpServletRequest request) {

		// TODO
		String purchaseOrderID = request.getParameter("purchaseOrderID");
		List<TPurchaseOrder> purchaseOrders = this.purchaseOrderService
				.getByProperty("id", Long.parseLong(purchaseOrderID));
		TPurchaseOrder tPurchaseOrder = purchaseOrders.get(0);
		Set<TPurchaseOrderPayment> tPurchaseOrderPayment = tPurchaseOrder
				.gettPurchaseOrderPayment();
		
		
		Set<TPurchaseOrderPayment> oldtPurchaseOrderPaymentSet = tPurchaseOrder.gettPurchaseOrderPayment();
		List<TPurchaseOrderPayment> oldtPurchaseOrderPaymentList = new ArrayList<TPurchaseOrderPayment>(oldtPurchaseOrderPaymentSet);
		List<TPurchaseOrderPayment> tPurchaseOrderPaymentList = new ArrayList<TPurchaseOrderPayment>();
		for(int j = 0 ; j <oldtPurchaseOrderPaymentList.size() ; j++){
			TPurchaseOrderPayment oldtPurchaseOrderPayment = oldtPurchaseOrderPaymentList.get(j);
		    Integer	deliveryNote1 = isNull(oldtPurchaseOrderPayment.getDeliveryNote1());
		    Integer deliveryNoteAttachmentStatus1 = isNull(oldtPurchaseOrderPayment.getDeliveryNoteAttachmentStatus1());
		    Integer acceptanceReportAttachmentStatus = isNull(oldtPurchaseOrderPayment.getAcceptanceReportAttachmentStatus());
		    Integer invoiceAttachmentStatus1  = isNull(oldtPurchaseOrderPayment.getInvoiceAttachmentStatus1());
		    Long paidAmount = oldtPurchaseOrderPayment.getPaidAmount();
		    Long billedAmount =  oldtPurchaseOrderPayment.getBilledAmount();
		    //待发货  所有字段=0
		    if(deliveryNote1== 0 &&deliveryNoteAttachmentStatus1==0 && acceptanceReportAttachmentStatus==0 
		    		&&invoiceAttachmentStatus1 == 0 && (paidAmount==null||paidAmount==0)
		    		&& (billedAmount==null||billedAmount==0)){
		    	oldtPurchaseOrderPayment.setMilestoneType((short)1);
		    }
		    //已发货   delivery_note_1=1；其他字段=0
		     if (deliveryNote1==1&&deliveryNoteAttachmentStatus1==0 && acceptanceReportAttachmentStatus==0 
		    		&&invoiceAttachmentStatus1 == 0 && (paidAmount==null||paidAmount==0)
		    		&& (billedAmount==null||billedAmount==0)){
		    	oldtPurchaseOrderPayment.setMilestoneType((short)2);
		    }
		    //已验货  delivery_note_1=1 and delivery_note_attachment_status_1=1 且其他字段等于0
		     if(deliveryNote1==1&&deliveryNoteAttachmentStatus1==1 && acceptanceReportAttachmentStatus==0 
		    		&&invoiceAttachmentStatus1 == 0 && (paidAmount==null||paidAmount==0)
		    		&& (billedAmount==null||billedAmount==0)){
		    	oldtPurchaseOrderPayment.setMilestoneType((short)3);
		    }
		    //已验收  acceptance_report_attachment_status=1 且 invoice_attachment_status_1=0
		     if (acceptanceReportAttachmentStatus==1  &&invoiceAttachmentStatus1 == 0 ){
		    	oldtPurchaseOrderPayment.setMilestoneType((short)4);
		    }
		    //已收发票 invoice_attachment_status_1=1 且 paid amount<billed amount
		     if (invoiceAttachmentStatus1==1 && (paidAmount<billedAmount)){
		    	oldtPurchaseOrderPayment.setMilestoneType((short)5);
		    }
		    //已付款  paid amount = billed amount
		     if (paidAmount!=0&&billedAmount!=0&&paidAmount==billedAmount){
		    	oldtPurchaseOrderPayment.setMilestoneType((short)6);
		    }
		     tPurchaseOrderPaymentList.add(oldtPurchaseOrderPayment);
		     
		}
		
		Set<TPurchaseOrderPayment> set = new HashSet<TPurchaseOrderPayment>(tPurchaseOrderPaymentList);
		tPurchaseOrder.settPurchaseOrderPayment(set);
		
		

		List<TPurchaseOrderPayment> tPurchaseOrderPaymentList1 = new ArrayList<TPurchaseOrderPayment>(
				tPurchaseOrderPayment);
		model.addAttribute("tSalesOrderPayment", new TSalesOrderPayment());
		model.addAttribute("purchaseOrder", tPurchaseOrder);
		model.addAttribute("tPurchaseOrderPayment", tPurchaseOrderPaymentList1);
		return "client/order_estimate";
	}

	@RequestMapping(value = "/updateEstimateGrade", method = {
			RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public String updateEstimateGrade(Model model, HttpServletRequest request) {

		try {
			Long id = Long.parseLong(request.getParameter("vendorId"));
			String grade = request.getParameter("grade");
			String status = null;
			//request.getParameter("status");
			// 暂时不确定将此值保存在哪
			@SuppressWarnings("unused")
			String estimateDetail = request.getParameter("dataContent");

			TVendor vendor = this.vendorService.getObject(id);
			if(grade=="E")
			{
				vendor.setStatus((short)4);
			}
			vendor.setGrade(grade);
			vendor.setGradeFromDate(new Date());
			vendor.setGradeToDate(ConvertTime.plusDaysDate(new Date(), Constants.ONE_YEAR));
			
			vendor.setGmtUpdateTime(new Date());
			this.vendorService.save(vendor);
			
			return JsonUtil
					.serialize(new CommonResponseDto<>(RetCodeEnum.SUCCESS
							.getCode(), RetCodeEnum.SUCCESS.getMsg()));
		} catch (Exception e) {
			return JsonUtil.serialize(new CommonResponseDto<String>(
					RetCodeEnum.FAIL.getCode(), e.getMessage()));
		}
	}

	/**
	 * C4-3评估页面,
	 * 
	 * @param model
	 * @param describe
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/updateOrderEstimate", method = {
			RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public String updateOrderEstimate(Model model,
			@RequestBody String describe, HttpServletRequest request) {

		try {
			Long id = Long.parseLong(request.getParameter("purchaseOrderId"));
			String grade2=request.getParameter("grade2");
			if("".equals(grade2)||null==grade2){
				grade2 = "0" ;
			}
			
			String grade3=request.getParameter("grade3");
			if("".equals(grade3)||null==grade3){
				grade3 = "0" ;
			}
			
			String grade4=request.getParameter("grade4");
			if("".equals(grade4)||null==grade4){
				grade4 = "0" ;
			}
			
			String grade5=request.getParameter("grade5");
			if("".equals(grade5)||null==grade5){
				grade5 = "0" ;
			}
			
			
			// String status=request.getParameter("status");
			// 暂时不确定将此值保存在哪
			String estimateDescribe = describe;

			UserDTO userDTO = CurrentUserUtils.getInstance().getUser();

			// 保存在T_Purchase_Order表
			this.purchaseOrderService.updatePurchaseEstimateManyGrade(id, estimateDescribe,grade2,grade3,grade4,grade5, new Date(), userDTO.getUsername());
			// 保存在T_Sales_Order表
			this.salesOrderService.updateSalesEstimate(id, estimateDescribe,grade2,
					new Date(), userDTO.getUsername());

			return JsonUtil
					.serialize(new CommonResponseDto<>(RetCodeEnum.SUCCESS
							.getCode(), RetCodeEnum.SUCCESS.getMsg()));
		} catch (Exception e) {
			System.out.println(e.toString());
			return JsonUtil.serialize(new CommonResponseDto<String>(
					RetCodeEnum.FAIL.getCode(), e.getMessage()));
		}

	}

	/**
	 * C4-2页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/confirmAttachmentStatus", method = {
			RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public String confirmAttachmentStatus(Model model,
			HttpServletRequest request) {

		try {
			Long id = Long.parseLong(request.getParameter("paymentId"));
			Boolean isStatus1 = Boolean.parseBoolean(request
					.getParameter("isStatus1"));
			Boolean isReport = Boolean.parseBoolean(request
					.getParameter("isReport"));

			// 确认验证报告
			if (isReport) {
				// 保存在T_Purchase_Order_Payment表,已确认
				this.purchaseOrderPaymentService.updatePurchaseReportStatus(
						isStatus1, id, Constants.AUDITED);
				// 保存在T_Sales_Order_Payment表
				this.salesOrderPaymentService.updateSalesReportStatus(
						isStatus1, id, Constants.AUDITED);
			} else// 确认发票
			{
				// 保存在T_Purchase_Order_Payment表,已确认
				this.purchaseOrderPaymentService.updatePurchaseInvoiceStatus(
						isStatus1, id, Constants.AUDITED);
				// 保存在T_Sales_Order_Payment表
				this.salesOrderPaymentService.updateSalesInvoiceStatus(
						isStatus1, id, Constants.AUDITED);
			}
			return JsonUtil
					.serialize(new CommonResponseDto<>(RetCodeEnum.SUCCESS
							.getCode(), RetCodeEnum.SUCCESS.getMsg()));
		} catch (Exception e) {
			return JsonUtil.serialize(new CommonResponseDto<String>(
					RetCodeEnum.FAIL.getCode(), e.getMessage()));
		}

	}

	@Override
	protected Class<?> getCurrentClass() {

		return ClientController.class;
	}

}
